var currentPage = 1;
var currentSize = 10;
var num = 0;
var records = [];
var id = '';
//新增对象
var addForm = {};
var updateForm = {};
var info = {};
var priKey = "";
var chainId = 0;
var contractList = [];
// 搜索
$('#searchBt').click(function () {
    for (var key in searchForm) {
        if (key != 'current' || key !== 'size') {
            searchForm[key] = $('#' + key).val();
        }
    }
    for (var key in searchForm) {
        if (key != 'current' || key !== 'size') {
            console.log(key, searchForm[key]);
        }
    }
    $getData();
})

// 清空
$('#reset').click(function () {
    for (var key in searchForm) {
        if (key != 'current' || key !== 'size') {
            $('#' + key).val('');
            searchForm[key] = $('#' + key).val();
        }
    }
    $getData();
})



//初始化实现数据
function initProvince() {
    var template = '';
    $.each(province, function(i, x){
        template += "<li data-value="+x.name+">"+x.name+"</li>"
    })
    setTimeout(function () {
        $('#myul').empty().append(template);
    },500)
}

function getCity() {
    var province = $('#region').val();
    for (var cityKey in city) {
       if (cityKey === province){
           var cityList =  city[cityKey];
           var template = '';
           $.each(cityList, function(i, x){
               template += "<li data-value="+x.name+">"+x.name+"</li>"
           })
           $('#my_city').empty().append(template);
       }

    }
}

//解锁钱包
function unlockPurse(e) {
    var _id = $(e).attr('data-href');
    $(_id).fadeIn("normal");
    $('.pop-bg').addClass('open');
}
//获取私钥
function getChainId(){
    chainId = "69";
    return chainId;
}
//获取私钥
function getPriKey(){
    priKey = "0xe73196d46547b84eb9ed02e610a9fcd4b1262a308466ed01c415b10a21bd6f29";
    return priKey;
}
//获取字典信息
function getUserChainSub() {
    $request({
        url: '/bmsApi/blade-blockchain/chain-sub/getUserChainSub?bid='+info.bid,
        method: 'get'
    }, function (res) {
        $.each(res, function(i, x){
            $('#zl').append(" <li data-value="+x.id+">"+x.name+"</li>")
        })
    })
}

//获取关联合约
function getRelationSubPage(chainId) {
    $request({
        url: '/bmsApi/blade-blockchain/sub-contract/relationSubPage?chainId='+chainId+"&current=1&size=20",
        method: 'get'
    }, function (res) {
        contractList = res.records;
        $.each(res, function(i, x){
            $('#relation').append(" <li data-value="+x.id+">"+x.name+"</li>")
        })
    })
}

//获取个人信息
function getUserInfo() {
    $request({
        url: '/bmsApi/blade-user/info',
        method: 'get'
    }, function (res) {
        info = res;
    })
}

//保存
function $save(addForm,url) {
    console.log(JSON.stringify(addForm));
    if (url){
        save_url = url;
    }
    $request({
        url: save_url,
        method: 'post',
        contentType: 'application/json;charset=UTF-8',
        data:JSON.stringify(addForm)
    },function () {
        history.go(-1);
        location.reload();
    })
}
//获取详细数据
function getDetailById() {
    $request({
        url: detail_url + id,
        method: 'get'
    }, function (res) {
        if (res){
            renderRecords(res)
        }
    })
}

//禁用-弹窗
function forbidden(e,id_) {
    id = id_;
    var _id = $(e).attr('data-href');
    $(_id).fadeIn("normal");
    $('.pop-bg').addClass('open');
}

//提交禁用表单
function $submitAudit(status) {
    var formData = {};
    if (status === 1 ||  status === 3){
        formData.approveReason = $('#approveReason_').val();
    }else {
        formData.approveReason = $('#approveReason').val();
    }
    if (!formData.approveReason){
        alert("原因不能为空！")
        return;
    }
    formData.status = status;
    formData.id = id;
    console.log(formData);
    $save(formData,audit_url);
}

//下载
function $download(url,id) {
    if (id){
        url = url+id;
    }
    window.open(url);
}

function downloadFile() {
    $request({
        url: download_url + id,
        method: 'get'
    }, function (res) {
        if (res.code === 400){
            alert(res.msg);
        }else {
            window.open(download_url+id);
        }
    })
}

// url 取参数
function $baseDictionary(code, type) {
    var codes = [];
    $request({
        url: '/bmsApi/blade-system/dict/dictionary?code=' + code,
        method: 'get'
    }, function (res) {
        if (res) {
            $(type).children().remove();
            res.sort(objectSort("dictKey"))
            $.each(res, function(i, x){
                $(type).append("<li data-value='" + x.dictKey + "'>" + x.dictValue + "</li>")
                codes[i] = x.dictValue;
            })
        }
    })
    return codes;
}

//对象排序
function objectSort(property) {
    return function (Obj1, Obj2) {
        return Obj1[property] - Obj2[property]
    }
}

//  确认提交
function $submitDeleteById() {
    addForm.priKey = $('#priKey').val();
    addForm.id = id;
    var flag = true;
    if (getPriKey() !== addForm.priKey){
        alert("私钥错误!");
        flag = false;
    }
    if (flag){
        $request({
            url: $delete_url,
            method: 'post',
            data: JSON.stringify(addForm)
        }, function (res) {
            alert("删除成功！")
            setTimeout(function () {
                location.reload();
            },500)
        })
    }
}

// 删除弹框
function dict_delete(index, e) {
    var _id = $(e).attr('data-href');
    $(_id).fadeIn("normal");
    $('.pop-bg').addClass('open');
    id = index
};

// 删除弹框-解锁钱包
function dict_js_qb(index, e) {
    var _id = $(e).attr('data-href');
    $(_id).fadeIn("normal");
    $('.pop-bg').addClass('open');
};

// 获取列表数据
function $getData() {
    searchForm.current = currentPage;
    searchForm.size = currentSize;
    $request({
        url: buildUrl(searchForm),
        method: 'get'
    }, function (res) {
        $('#bms_table').children().remove();
        $('.none-data').remove();
        if (res.records.length > 0) {
            renderRecords(res.records);
        } else {
            $('.table1-body').append("<div class='none-data'><p>暂无数据</p></div>");
        }
        records = res.records
        if (res.total) {
            console.log('restotal', res.total)
            $('#pageable').show()
            $('#total').html("共" + res.total + "条")
            num = Math.ceil(res.total / currentSize);
            pageNumInit(num)
        } else {
            $('#pageable').hide()
        }
        //回滚url
        url_ = url;
    })
}

//构件请求地址
function buildUrl(searchForm, url) {
    var count = 0;
    if (url) {
        url_ = url;
    }
    for (var key in searchForm) {
        if (key === 'chainType') {
            searchForm[key] = 0;
        }
        if (count === 0 && url_.indexOf(key) === -1) {
            url_ += key + "=" + searchForm[key];
        } else if (count > 0 && url_.indexOf(key) === -1) {
            url_ += "&" + key + "=" + searchForm[key];
        }
        count++
    }
    console.log(url_);
    return url_;
}

//-----------------------------分页-------------------------
// 分页页码
function pageNumInit(num) {
    $('#pageList').children().remove();
    if (currentPage === 1 && currentPage !== num) {
        $('#pageList').append(
            "<li class='pages-prev pages-disable'><a href='javascript:;'><i class='el-icon el-icon-arrow-left'></i></a></li>" +
            getPageNum(num) +
            "<li class='pages-next' onclick='changePageSize(" + currentSize + "," + (currentPage + 1) + ",this)'><a href='javascript:;'><i class='el-icon el-icon-arrow-right'></i></a></li>"
        );
    } else if (currentPage === num && currentPage !== 1) {
        $('#pageList').append(
            "<li class='pages-prev' onclick='changePageSize(" + currentSize + "," + (currentPage - 1) + ",this)'><a href='javascript:;'><i class='el-icon el-icon-arrow-left'></i></a></li>" +
            getPageNum(num) +
            "<li class='pages-next pages-disable'><a href='javascript:;'><i class='el-icon el-icon-arrow-right'></i></a></li>"
        );
    } else if (currentPage === 1 && currentPage === num) {
        $('#pageList').append(
            "<li class='pages-prev pages-disable'><a href='javascript:;'><i class='el-icon el-icon-arrow-left'></i></a></li>" +
            getPageNum(num) +
            "<li class='pages-next pages-disable'><a href='javascript:;'><i class='el-icon el-icon-arrow-right'></i></a></li>"
        );
    } else {
        $('#pageList').append(
            "<li class='pages-prev' onclick='changePageSize(" + currentSize + "," + (currentPage - 1) + ",this)'><a href='javascript:;'><i class='el-icon el-icon-arrow-left'></i></a></li>" +
            getPageNum(num) +
            "<li class='pages-next' onclick='changePageSize(" + currentSize + "," + (currentPage + 1) + ", this)'><a href='javascript:;'><i class='el-icon el-icon-arrow-right'></i></a></li>"
        );
    }
}

// 分页拼接
function getPageNum(num) {
    var result = '';
    for (var i = 0; i < num; i++) {
        if (i === 0) {
            result += "<li class='pages-active' onclick='changePageSize(" + currentSize + "," + 1 + ",this)'><a href='javascript:;'>1</a></li>";
        } else {
            result += "<li onclick='changePageSize(" + currentSize + "," + (i + 1) + ",this)'><a href='javascript:;'>" + (i + 1) + "</a></li>";
        }
    }
    return result;
}

// 改变每页条数
function changePageSize(size, pageNo, current) {
    var page = pageNo ? pageNo : $('#pageNum').val() ? $('#pageNum').val() : 1;
    currentSize = size ? size : 10;
    currentPage = Number(page);
    $getData();
    pageNumInit(num);
}

// 改变页码
function changeCurrentPage() {
    var page = $('#pageNum').val() ? $('#pageNum').val() : currentPage
    currentPage = Number(page)
    $getData();
}

// 批量上报
$('#file').change(function(e) {
    console.log('e', e)
    var bladeAuth = 'bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0ZW5hbnRfaWQiOiIwMDAwMDAiLCJ1c2VyX25hbWUiOiI4MzM0NThlNC01OTA0LTQyMTctYmE3NS02ODQ3MzBiNjlkNmYiLCJyZWFsX25hbWUiOiLlpaXlt7TpqawiLCJhdmF0YXIiOiIiLCJhdXRob3JpdGllcyI6WyJiaWRfY2VydGlmaWNhdGVfYWRtaW4iLCJjaGFpbnN1Yl9hZG1pbiIsImJpZF9jaGFpbl9hZG1pbiJdLCJjbGllbnRfaWQiOiJzYWJlciIsImNlcnRpZmljYXRlX3N0YXR1cyI6bnVsbCwicm9sZV9uYW1lIjoiY2hhaW5zdWJfYWRtaW4sYmlkX2NoYWluX2FkbWluLGJpZF9jZXJ0aWZpY2F0ZV9hZG1pbiIsImxpY2Vuc2UiOiJwb3dlcmVkIGJ5IGJsYWRleCIsInVzZXJfdHlwZSI6LTEsInBvc3RfaWQiOiIxMTIzNTk4ODE3NzM4Njc1MjA4IiwiYXZhdGFyX3VybCI6IiIsInVzZXJfaWQiOiIxNTA0NzU4OTMzNTM1OTgxNTcwIiwicm9sZV9pZCI6IjExMjM1OTg4MTY3Mzg2NzUyMDEiLCJzY29wZSI6WyJhbGwiXSwibmlja19uYW1lIjoi5aWl5be06amsIiwiZXhwIjoxNjU1MTAwOTk2LCJkZXB0X2lkIjoiMSIsImp0aSI6IjhkZDU4ODFmLWZmYmQtNDljYy05NTQzLTdiNThiMTI2ODEwZSIsImFjY291bnQiOiI4MzM0NThlNC01OTA0LTQyMTctYmE3NS02ODQ3MzBiNjlkNmYifQ.t6IUqXZC99gN17GoAHSNO196kAX21_f_PrPIl1_I4tc';
    var file = e.target.files[0]
    var fd = new FormData()
    fd.append('file', file)
    $.ajax({
        url: '/bmsApi/blade-blockchain/excle/upChainSubBlockUpExcle',
        method: 'post',
        beforeSend: function (req) {
            // test
            // req.setRequestHeader('Auth', getUuid())
            req.setRequestHeader('Auth', '72586d00-ee92-4039-9bf5-468e0e43cc6a')
            // req.setRequestHeader('Authorization', "bearer " + localStorage.getItem("ACCESS_TOKEN"))
            req.setRequestHeader('Authorization', 'Basic c2FiZXI6c2FiZXJfc2VjcmV0')
            req.setRequestHeader('Blade-Auth', bladeAuth)
            // req.setRequestHeader('check', localStorage.getItem("username"))
            req.setRequestHeader('check', '833458e4-5904-4217-ba75-684730b69d6f')
        },
        processData: false,
        contentType: false,
        data: fd,
        // headers: {
        //     'Content-Type': 'multipart/form-data'
        // },
        success: function(res) {
            console.log('res', res)
            if (res.data.chainSubBlockUp && res.data.chainSubBlockUp.length) {
                var str = ''
                for(var i = 0; i < res.data.chainSubBlockUp.length; i++) {
                    str+= (i + 1) + '. ' + res.data.chainSubBlockUp[i].error
                }
                alert(str)
            } else {
                location.reload()
            }
        },
        fail: function(err) {
            console.log('err', err)
        }
    })
})
